package com.controller;

import com.model.OrderModel;
import com.services.IOrderServices;
import com.services.impl.OrderServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/orders")
public class OrderCreateServletController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 读取请求体
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JSONObject jsonData = JSONObject.fromObject(sb.toString());
            
            // 创建订单对象
            OrderModel orderModel = new OrderModel();
            orderModel.setFlightId(jsonData.getInt("flightId"));
            orderModel.setTicketType(jsonData.getString("ticketType"));
            orderModel.setQuantity(jsonData.getInt("quantity"));
            orderModel.setPassengers(jsonData.getJSONArray("passengers"));
            
            // 获取用户信息（假设从session中获取）
            // String userEmail = (String) request.getSession().getAttribute("userEmail");
            // orderModel.setUserEmail(userEmail);
            
            // 创建订单
            IOrderServices orderServices = new OrderServicesImpl();
            OrderModel createdOrder = orderServices.createOrder(orderModel);
            
            result.put("code", 0);
            result.put("msg", "订单创建成功");
            result.put("data", createdOrder);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "创建订单失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }
} 